package com.fy56.platform.logistics.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.Order;
import com.fy56.platform.logistics.service.wx.ICompanyInfoService;
import com.fy56.platform.logistics.service.wx.IGoodsTraceService;
import com.fy56.platform.logistics.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zeus.base.privilege.model.TbCompany;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.fy56.platform.logistics.utils.HttpUtil.setHeader;

/**
 * Created by Administrator on 2018-06-19.
 */
@Service
public class GoodsTraceServiceImpl implements IGoodsTraceService {

    @Autowired
    private ICompanyInfoService iCompanyInfoService;

    private String setParam(Map<String, String> map) {
        String param = "param=" + JSONObject.toJSONString(map);
        return param;
    }
    @Override
    public Map<String, Object>  getGoodsTracesFromTrack(String trackingNo) throws Exception {

        //初始化返回值
        List<Order> list = Lists.newArrayList();

        Map<String, String> paramMap = Maps.newHashMap();
        //当前页数
        paramMap.put("trackingNo", trackingNo);
        //每页显示个数
        paramMap.put("companySearch", "1");
        //开始日期
        Map<String, Object> resultMap =Maps.newHashMap();
        //请求处理
        String result = null;
        try {
            String url =StaticUtil.TRACE_OHM_ORDER_URL;
            url=url.replace("ohmOrderManager/queryOhmOrderList","ohmOrderRouteManager/queryOrderRoute");
            result = HttpClientUtils.postParameters(url, setParam(paramMap));
            if (StringUtil.isNotEmpty(result)) {
                resultMap = JSON.parseObject(result);

            } else {
                throw new Exception("请求货物跟踪平台失败或无返回值！");
            }
        } catch (JSONException e) {
            throw new Exception("请求货物跟踪平台出错，请联系管理员！", e);
        } catch (SocketTimeoutException e) {
            throw new Exception("请求货物跟踪平台超时，请联系管理员！", e);
        } catch (Exception e) {
            throw new Exception(e.getMessage() == null ? "服务端出错！" : e.getMessage(), e);
        }

        return resultMap;
    }
    /**
     * 根据金融代码和票号查询货物跟踪
     *
     * @param code 金融代码
     * @param orderNo 票号
     * @return
     */
    @Override
    public Map<String, Object> getGoodsTracesFromBSOrF6(String code, String orderNo) throws Exception {
        Long begin = System.currentTimeMillis();//开始时间
        //初始化返回值
        Map<String, Object> info = Maps.newHashMap();

        //根据金融代码获取公司信息，如果获取不到，抛出异常
        Company company = iCompanyInfoService.getCompanyByCode(code);
        if(company == null){
            throw new Exception("该企业[" + code + "]已被删除！");
        }

        //请求地址(如果是F6系统，则帐套名称和组织代码必须传)
        String url = company.getUrl()+"/goodsTraces/getGoodsTracesByOrderNo?orderNo=" + orderNo;
        if(StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())){
            url += "&accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }

        //请求处理
        String result = null;
        try {
            result = HttpUtil.get(url);
            Long end = System.currentTimeMillis();//结束时间
            System.out.print("货物跟踪请求F6用时：" + (end - begin) + "毫秒。");
            if(StringUtil.isNotEmpty(result)){
                ResultModel model = JSON.parseObject(result,ResultModel.class);
                if(200 == model.getCode()){
                    if("SUCCESS".equals(model.getMsg())){
                        //票号
                        info.put("orderNo",orderNo);
                        Map<String,Object> map = (Map<String,Object>) model.getContent();
                        //货物跟踪的集合
                        info.put("list",map.get("list"));
                        info.put("company",company);
                        setGoodsTrace(info,map,company);
                        Long e = System.currentTimeMillis();//结束时间
                        System.out.print("货物跟踪总用时：" + (e - begin) + "毫秒。");
                        return info;
                    }else{
                        throw new Exception("从F6或BS服务端获取货物跟踪失败！" + model.getMsg());
                    }
                }else{
                    throw new Exception("从F6或BS服务端获取货物跟踪失败！" + model.getMsg());
                }
            }else{
                throw new Exception("请求F6或BS服务端失败或无返回值！");
            }
        } catch (JSONException e) {
            throw new Exception("请求F6或BS服务端出错，请联系管理员！",e);
        }  catch (SocketTimeoutException e) {
            throw new Exception("请求F6或BS服务端超时，请联系管理员！",e);
        } catch (Exception e) {
            throw new Exception(e.getMessage() == null ? "服务端出错！" : e.getMessage(),e);
        }
    }

    /**
     * 设置货物跟踪地图描点需要的属性
     *
     * @param goodsTrace
     * @param map
     * @param company
     */
    private void setGoodsTrace(Map<String, Object> goodsTrace, Map<String,Object> map, Company company){
        try{
            //获取从认证中心获取所有子公司信息
            List<TbCompany> subCompanyList =null;
            //20200414 lml 改成http方式请求腾云获取公司信息
            try{
                Map<String, String> paramsNew = Maps.newHashMap();
                paramsNew.put("companyCode",company.getCode());
                paramsNew.put("passWord", MD5Util.getMD5Code(company.getTenantPass()));
                paramsNew.put("parentId",company.getId()+"");
                String result = HttpClientUtils.post( StaticUtil.restSearchURL+"/privilegeManager/selectByParentId", paramsNew, setHeader(), 20000, 20000);
                if(result!=null){
                    JSONObject j = JSON.parseObject(result);
                    String  object=j.get("object")+"";
                    subCompanyList= JSON.parseArray(object, TbCompany.class);
                }
            }catch (Exception e){
                System.out.println(e);
            }
            if(CollectionUtils.isNotEmpty(subCompanyList)){
                for(TbCompany tbCompany : subCompanyList){
                    if(map.get("placeOfLoading").toString().equals(tbCompany.getCompanyNameAlias())){
                        goodsTrace.put("placeOfLoadingLongitude",tbCompany.getLongitude());
                        goodsTrace.put("placeOfLoadingLatitude",tbCompany.getLatitude());
                    }
                    if(map.get("sendCompany").toString().equals(tbCompany.getCompanyNameAlias())){
                        goodsTrace.put("sendCompanyLongitude",tbCompany.getLongitude());
                        goodsTrace.put("sendCompanyLatitude",tbCompany.getLatitude());
                    }
                    if(map.get("receiveCompany").toString().equals(tbCompany.getCompanyNameAlias())){
                        goodsTrace.put("receiveCompanyLongitude",tbCompany.getLongitude());
                        goodsTrace.put("receiveCompanyLatitude",tbCompany.getLatitude());
                    }
                }
                if(map.get("senderAddress") != null && map.get("senderAddress").toString().length() > 0){
                    if(map.get("placeOfLoading").toString().equals(map.get("senderAddress").toString())){
                        goodsTrace.put("senderAddress","");
                    }else{
                        //发货人地址
                        goodsTrace.put("senderAddress",map.get("senderAddress").toString());
                    }
                    //发货人经度
                    goodsTrace.put("senderLongitude",map.get("senderLongitude") == null ? "" : map.get("senderLongitude"));
                    //发货人纬度
                    goodsTrace.put("senderLatitude",map.get("senderLatitude") == null ? "" : map.get("senderLatitude"));
                }else{
                    goodsTrace.put("senderAddress","");
                    //发货人经度
                    goodsTrace.put("senderLongitude",goodsTrace.get("placeOfLoadingLongitude"));
                    //发货人纬度
                    goodsTrace.put("senderLatitude",goodsTrace.get("placeOfLoadingLatitude"));
                }

                //开票地点
                goodsTrace.put("placeOfLoading",map.get("placeOfLoading").toString());
                if(map.get("placeOfLoading").toString().equals(map.get("sendCompany").toString())){
                    //发货公司
                    goodsTrace.put("sendCompany","");
                }else{
                    //发货公司
                    goodsTrace.put("sendCompany",map.get("sendCompany").toString());
                }
                //到货公司
                goodsTrace.put("receiveCompany",map.get("receiveCompany").toString());

                //定位小车位置和文字(1.发货人地址 2.开票地点 3.发货公司 4.到货公司)
                String content1 = "";
                String content2 = "";
                String content3 = "";
                String content4 = "";
                if("1".equals(map.get("currentStatus").toString())){
                    goodsTrace.put("carLongitude",goodsTrace.get("senderLongitude"));
                    goodsTrace.put("carLatitude",goodsTrace.get("senderLatitude"));
                    content1 = "已揽件";
                }else if("2".equals(map.get("currentStatus").toString())){
                    goodsTrace.put("carLongitude",goodsTrace.get("placeOfLoadingLongitude"));
                    goodsTrace.put("carLatitude",goodsTrace.get("placeOfLoadingLatitude"));
                    content2 = "已提货";
                } else if("3".equals(map.get("currentStatus").toString())){
                    goodsTrace.put("carLongitude",goodsTrace.get("sendCompanyLongitude"));
                    goodsTrace.put("carLatitude",goodsTrace.get("sendCompanyLatitude"));
                    content3 = "已配载";
                }else{
                    goodsTrace.put("carLongitude",goodsTrace.get("receiveCompanyLongitude"));
                    goodsTrace.put("carLatitude",goodsTrace.get("receiveCompanyLatitude"));
                    content4 = "已到达";
                }
                goodsTrace.put("content1",content1);
                goodsTrace.put("content2",content2);
                goodsTrace.put("content3",content3);
                goodsTrace.put("content4",content4);
            }
        }catch (Exception e){
            System.out.println("拼接货物跟踪信息失败---------------------");
            System.out.println(e);
            return;
        }
    }

}
